#include	"router.h"
#include	"utils/logger.h"

Router & Router::Get() {
	static Router * pIns = nullptr;
	if (!pIns) pIns = new Router;
	return *pIns;
}

void Router::Register(const std::string & sMethod, const std::string & sRouter, int nProcRef) {
	Api iApi;
	iApi.iRouter	= std::regex(sRouter);
	iApi.sMethod	= sMethod;
	iApi.nProcRef	= nProcRef;

	_vApis.push_back(iApi);
}

int Router::Match(const std::string & sMethod, const std::string & sUrl, int & nProc, std::smatch & rMatch) {
	bool bFound = false;
	bool bUse = false;

	for (auto & r : _vApis) {
		if (regex_match(sUrl, rMatch, r.iRouter)) {
			bFound = true;
			if (r.sMethod == "ANY" || r.sMethod == sMethod) {
				bUse	= true;
				nProc	= r.nProcRef;
				break;
			}
		}
	}

	if (!bFound) return 404;
	if (!bUse) return 405;
	return 200;
}

